package com.cnnp.dip.api.client;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.stereotype.Component;

import com.cnnp.dip.api.config.GrafanaConfig;

import feign.Feign;
import feign.Logger;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.slf4j.Slf4jLogger;

@Component
public class GrafanaClientFactory {

    private final GrafanaConfig grafanaConfig;
    private final Map<Class<?>, Object> feignClientsCache = new ConcurrentHashMap<>();

    public GrafanaClientFactory(GrafanaConfig grafanaConfig) {
        this.grafanaConfig = grafanaConfig;
    }

    /**
     * 通用的Feign客户端创建方法
     * @param <T> Feign客户端接口类型
     * @param clazz Feign客户端接口Class对象
     * @return 创建的Feign客户端实例
     */
    public <T> T createFeignClient(Class<T> clazz) {
        return Feign.builder()
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .logger(new Slf4jLogger(clazz))
                .logLevel(Logger.Level.FULL)
                .contract(new SpringMvcContract())
                .target(clazz, grafanaConfig.getBaseUrl());
    }

    /**
     * 获取AnnotationApi客户端（兼容旧代码）
     * @return AnnotationApi实例
     */
    public GrafanaAnnotationApi getGrafanaFeignClient() {
        return createFeignClient(GrafanaAnnotationApi.class);
    }

    public GrafanaSearchApi getSearchApi() {
        return createFeignClient(GrafanaSearchApi.class);
    }

    public synchronized <T> T getOrCreateFeignClient(Class<T> clazz) {
        @SuppressWarnings("unchecked")
        T client = (T) feignClientsCache.get(clazz);
        if (client == null) {
            client = createFeignClient(clazz);
            feignClientsCache.put(clazz, client);
        }
        return client;
    }
} 